<?php
/**
 *  网页截图服务，支持windows和linux平台
 * ============================================================================
 * 版权所有:  西安尊云信息科技有限公司，并保留所有权利。
 * 网站地址:  http://www.zunyunkeji.com
 * ----------------------------------------------------------------------------
 * 许可声明：遵循GPL2.0开源协议
 * ============================================================================
 * Author: 缘境 (yvsm@zunyunkeji.com) QQ:316430983 
*/


namespace zunyunkeji;

class ScreenShot{
	
	protected $port = 3164;
    protected $timeOut = 5000;
    protected $javascriptEnabled = false;
    protected $width = 1440;
    protected $height = 800;
    protected $logPath = '';

    public function __construct(){
		if(!in_array(PHP_OS,['WINNT','Linux'])){
			throw new ScreenServerException('暂不支持此操作系统', 400);
		}
    }
	
    public function getPort()
    {
        return $this->port;
    }

    public function setPort($port)
    {
        $this->port = $port;
    }

    public function getTimeOut()
    {
        return $this->timeOut;
    }

    public function setTimeOut($timeOut)
    {
        $this->timeOut = $timeOut;
        return $this;
    }


    protected function basePath()
    {
        return __DIR__ . DIRECTORY_SEPARATOR;
    }

    protected function binPath()
    {
        return $this->basePath() . 'bin' . DIRECTORY_SEPARATOR;
    }

    protected function scriptPath()
    {
        return $this->basePath() . 'scripts' . DIRECTORY_SEPARATOR;
    }

    protected function logPath()
    {
        if ($logPath = $this->getLogPath()) {
            return $logPath;
        }
        return dirname($this->basePath()) . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR;
    }

    protected function logFile()
    {
        $logFile = $this->logPath() . 'screenshot_'.date('ymd').'.log';
        if (!is_dir(dirname($logFile))) @mkdir(dirname($logFile), 0777, true);
        if (!file_exists($logFile)) file_put_contents($logFile, '', FILE_APPEND);
        return $logFile;
    }
	
    public function isJavascriptEnabled()
    {
        return $this->javascriptEnabled ? 'true' : 'false';
    }

    public function setJavascriptEnabled($javascriptEnabled)
    {
        $this->javascriptEnabled = $javascriptEnabled;
        return $this;
    }

    public function getWidth()
    {
        return $this->width;
    }

    public function setWidth($width)
    {
        $this->width = $width;

        return $this;
    }

    public function getHeight()
    {
        return $this->height;
        return $this;
    }

    public function setHeight($height)
    {
        $this->height = $height;
        return $this;
    }

    /**
     * @return string
     */
    public function getLogPath()
    {
        return $this->logPath;
    }

    /**
     * @param string $logPath
     */
    public function setLogPath($logPath)
    {
        $this->logPath = $logPath;
        return $this;
    }


    public function isRunning(){
		if(PHP_OS=='WINNT'){
			exec('wmic process where name="phantomjs.exe" get name', $output);
			return (bool) array_shift($output);
        }else if(PHP_OS=='Linux'){
            exec('ps | grep phantomjs', $output);
			return count($output);
        }else{
			throw new ScreenServerException('暂不支持此操作系统', 400);
		}
		
        return $this->isRunning();
    }

    public function start(){
        if ($this->isRunning()) return;

        $this->compileServer();

		if(PHP_OS=='WINNT'){
			$shell = "start /B %sphantomjs --ignore-ssl-errors=true --ssl-protocol=any %sserver.js >> %s";
			$command = sprintf($shell, $this->binPath(), $this->scriptPath(), $this->logFile());
			var_dump($command);
			exec($command);
		}else if(PHP_OS=='Linux'){
			$shell = "%sphantomjs --ignore-ssl-errors=true --ssl-protocol=any %sserver.js >> %s";
			$command = sprintf($shell, $this->binPath(), $this->scriptPath(), $this->logFile());
			exec($command);
		}else{
			throw new ScreenServerException('暂不支持此操作系统', 400);
		}
    }

    public function stop(){
		if(PHP_OS=='WINNT'){
			exec('wmic process where name="phantomjs.exe" delete');
		}else if(PHP_OS=='Linux'){
			exec('pkill -f "phantomjs"');
		}else{
			throw new ScreenServerException('暂不支持此操作系统', 400);
		}
    }

    public function shot($url)
    {
        $this->start();
        header("content-type: image/png");
        $img = $this->get_url_content('http://127.0.0.1:' . $this->getPort() . '/?a=' . $url);

        echo base64_decode($img);
    }

    public function getShot($url)
    {
        $this->start();
        $img = $this->get_url_content('http://127.0.0.1:' . $this->getPort() . '/?a=' . $url);
        return $img;
    }
	
	
    public function compileServer()
    {
		$date = date('Y-m-d H:i:s');
        $script = <<<JS
var webserver = require('webserver');
var server = webserver.create();
var webpage = require('webpage');

var service = server.listen({$this->port}, function (request, response) {
/* zydir.com {$date} */
    var page = webpage.create(), address;

    page.settings.resourceTimeout = {$this->timeOut};

    page.settings.javascriptEnabled = {$this->isJavascriptEnabled()};

    page.viewportSize = {width: {$this->width}, height: {$this->height}};

    address = request.url.substr(4);

    page.open(address, function (status) {
        if (status !== 'success') {
            console.log('Unable to load the address!');
            response.write(0);
        } else {
            console.log(address);
            response.write(page.renderBase64('PNG'));
        }
        response.close();
        page.close();
    });

});
JS;
        file_put_contents(__DIR__ . '/scripts/server.js', $script);
    }
		
	/**
	 * 抓取网页内容
	 * @param string $url 网址
	 * @param intval $time_out 超时时间
	 * @author 尊云科技  <wdphp.cn>
	 * @return string
	*/
	public function get_url_content($url,$time_out=10) {
		if (empty($url))return false;
		if (substr($url, 0, 7) != 'http://') $url = 'http://'.$url;
		$data = '';
		$UserAgent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, 0);  //0表示不输出Header，1表示输出
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl, CURLOPT_TIMEOUT,$time_out);   //只需要设置一个秒的数量就可以  
		curl_setopt($curl, CURLOPT_ENCODING, '');
		curl_setopt($curl, CURLOPT_ENCODING, "gzip"); //压缩源代码   
		curl_setopt($curl, CURLOPT_USERAGENT, $UserAgent);
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
		$data = curl_exec($curl);
		return $data;
	}
}